package com.letoy.study.service.Impl;

import com.letoy.study.dao.UserMapper;
import com.letoy.study.entity.AuthUser;
import com.letoy.study.entity.PreRegisterUser;
import com.letoy.study.entity.TokenInfo;
import com.letoy.study.entity.User;
import com.letoy.study.service.MailService;
import com.letoy.study.service.TokenService;
import com.letoy.study.service.UserService;
import com.letoy.study.utils.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

import static com.letoy.study.utils.Constants.*;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    RedisUtil redisUtil;

    @Resource
    MailService mailService;

    @Resource
    TokenService tokenService;


    @Override
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    public String getUserIdByEmailPassword(String email, String password) {
        return null;
    }

    @Override
    public User getUserByEmailPassword(String email, String password) {
        return userMapper.getUserByEmailAndPassword(email, password);
    }

    @Override
    public User getUserByUserId(String userId) {
        return userMapper.getUserByUserId(userId);
    }

    @Override
    public String preRegisterUser(PreRegisterUser preRegisterUser) {
        String activeCode = RandomUtil.getCode();
        preRegisterUser.setActiveCode(activeCode);
        if(userMapper.getUserByEmail(preRegisterUser.getEmail()) == null){
            if (mailService.sendActivateCode(preRegisterUser.getEmail(), activeCode) == SUCCESS) {
                redisUtil.set(preRegisterUser.getEmail(), preRegisterUser);
                redisUtil.expire(preRegisterUser.getEmail(), 600L);
                return activeCode;
            } else {
                return null;
            }
        }else{
            return "EXIST";
        }

    }

    @Override
    public HashMap<String, Object> activeUser(String email, String activeCode) {
        HashMap<String, Object> map = new HashMap<>();
        BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil = new BCryptPasswordEncoderUtil();
        PreRegisterUser preRegisterUser = (PreRegisterUser) redisUtil.get(email);
        if (preRegisterUser != null) {
            if (activeCode.equals(preRegisterUser.getActiveCode())) {
                User user = new User();
                user.setEmail(email);
                user.setPassword(bCryptPasswordEncoderUtil.encode(preRegisterUser.getPassword()));
                String token = initUser(user);
                if (token != null) {
                    redisUtil.del(email);
                    map.put("status", SUCCESS);
                    map.put("token", token);
                } else {
                    map.put("status", FAIL);
                    map.put("msg", Constants.getMsg(FAIL));
                }
            } else {
                map.put("status", EXCEPTED_SYSTEM_ERROR);
                map.put("msg", Constants.getMsg(CODE_INVALID));
            }
        } else {
            map.put("status", EXCEPTED_SYSTEM_ERROR);
            map.put("msg", Constants.getMsg(CODE_NOT_EXIST));
        }
        return map;
    }

    @Override
    public String initUser(User user) {
        //1.生成Id，往用户库插入用户信息
        String userId = RandomUtil.getRandomId();
        user.setUserId(userId);
        user.setRole("NormalUser");
        userMapper.initUser(user);
        //2。往token_info初始化信息
        AuthUser authUser = new AuthUser();
        authUser.setId(userId);
        authUser.setEmail(user.getEmail());
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String systemToken = jwtTokenUtil.generateToken(authUser);
        //把新的token存储到缓存中
        TokenInfo tokenInfo = new TokenInfo();
        tokenInfo.setUserId(userId);
        tokenInfo.setSystemToken(systemToken);
        tokenService.addNewUser(tokenInfo);
        return systemToken;
    }
}
